﻿using System;
using System.Collections.Generic;
using System.Text;
using ClassLibrary.SignalType;
using ClassLibrary.SignalType.SynchronousTransportModuleLevel1.VirtualContainer;

namespace NetworkNode.Switching
{
    /// <summary>
    /// @Author Marcin Król
    /// </summary>
    class Adapter
    {
        private readonly VCType _vcType;

        readonly List<DataPackage> _dataPackageList = new List<DataPackage>();

        /// <param name="vcType">type of adapted virtual containers</param>
        public Adapter(VCType vcType)
        {
            _vcType = vcType;
        }

        /// <summary>
        /// used to adapt stream of data to SDH network
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public VirtualContainer AdaptObtainedData()
        {
            VirtualContainer virtualContainer = null;
            var dataPackage = AccumulateObtainedData();
            if (dataPackage != null)
            {
                if (_vcType == VCType.VC4)
                {
                    virtualContainer = new Vc4(dataPackage) {Poh = Utils.GeneratePoh()};
                }
                else
                {
                    virtualContainer = new Vc(_vcType, dataPackage){Poh = Utils.GeneratePoh()};
                }
            }
            //clear buffor
            _dataPackageList.Clear();
            return virtualContainer;
        }

        /// <summary>
        /// constructs singular dataPackage of all received
        /// </summary>
        /// <returns></returns>
        private DataPackage AccumulateObtainedData()
        {
            var dataStringBuilder = new StringBuilder();
            
            foreach (var dataPackage in _dataPackageList)
            {
                dataStringBuilder.Append(dataPackage.Data);
            }

            DataPackage accumDataPackage = null;
            String strData = dataStringBuilder.ToString();
            if (strData.Length > 0)
            {
                accumDataPackage = new DataPackage(strData);
            }
            return accumDataPackage;
        }

        public void ObtainDataPackage(DataPackage dataPackage)
        {
            _dataPackageList.Add(dataPackage);
        }

        /// <summary>
        /// used when realeasing data from sdh network
        /// </summary>
        /// <param name="virtualContainer"></param>
        /// <returns></returns>
        public static DataPackage Release(VirtualContainer virtualContainer)
        {
            return virtualContainer.DataPackage;
        }
    }
}
